package com.swl.juc.queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class QueueTest {
    static class Work implements Delayed {
        //名称
        private String name;
        //时长
        private long time;
        public Work(String name, long time, TimeUnit unit) {
            this.name = name;
            this.time = System.currentTimeMillis() + (time > 0 ? unit.toMillis(time) : 0);
        }
        //时间
        @Override
        public long getDelay(TimeUnit unit) {
            return time - System.currentTimeMillis();
        }
        @Override
        public int compareTo(Delayed o) {
            Work work = (Work) o;
            long diff = this.time - work.time;
            if (diff <= 0) {// 改成>=会造成问题
                return -1;
            } else {
                return 1;
            }
        }
    }
public static void main(String[] args) {
        BlockingQueue<Work> queue3 = new DelayQueue<>();
        try {
            Work work = new Work("用户一", 25, TimeUnit.SECONDS);
            Work work2 = new Work("用户二", 5, TimeUnit.SECONDS);
            Work work3 = new Work("用户三", 15, TimeUnit.SECONDS);
            queue3.add(work);
            queue3.add(work2);
            queue3.add(work3);
            for (; ; ) {
                Work work1 = queue3.take();
                System.out.println(work1.name + "," + work1.time);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}